<?php

class ORM extends ArrayObject {
	public $parentTable;
	public $childTable;
	public $relationship = 'oneToOne';
	public $joinCriteria = array();

	public function __construct($parentTable, $childTable, $config = '') {
		$this->parentTable = $parentTable;
		$this->childTable = $childTable;
		if(is_array($config)) $this->configure($config);
		if(empty($this->relationship) || empty($this->joinCriteria)) $this->autoConfig();
	}

	public function configure(array $config) {
		foreach($config as $opt => $val) {
			switch($opt) {
				//set each ORM property if found in config
				case 'relationship':
					switch($val) {
						case 'oneToOne':
						case 'oneToMany':
						case 'manyToOne':
						case 'manyToMany':
							$this->relationship = $val;
						break;
					}
				break;
				case 'on':
				case 'ON':
					// array('on' => array('t1.id' => 't2.id'))
					if(is_array($val)) $this->joinCriteria = $val;
				break;
			}
		}
	}
	
	private function getPrimaryKey($table) {
		if($primaryKey = DB::$db->getPrimaryKey($table)) return $primaryKey;
		return FALSE;
	}
	
	private function getForeignKey($table,$pkey) {
		if($foreignKey = DB::$db->getForeignKey($table,$pkey)) return $foreignKey;
		return FALSE;
	}
	
	private function autoConfig() {	
		if($parentKey = $this->getPrimaryKey($this->parentTable)) {
			if($childFKey = $this->getForeignKey($this->childTable,$parentKey)) {
				if(empty($this->relationship)) $this->relationship = 'oneToMany';
				if(empty($this->joinCriteria)) $this->joinCriteria = array($this->parentTable.'.'.$parentKey => $this->childTable.'.'.$childFKey);
			}
		}
		if(empty($this->joinCriteria)) {
			if($childKey = $this->getPrimaryKey($this->childTable)) {
				if($parentFKey = $this->getForeignKey($this->parentTable,$childKey)) {
					if(empty($this->relationship)) $this->relationship = 'manyToOne';
					if(empty($this->joinCriteria)) $this->joinCriteria = array($this->childTable.'.'.$childKey => $this->parentTable.'.'.$parentFKey);
				}
			}
		}
	}

}

?>